package com.ruoyi.stomp.controller;

import com.ruoyi.stomp.domain.ChatMsg;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.security.Principal;

/**
 * @ClassName ChatController
 * @Description 消息控制
 * @Author li yang
 * @Date 2025/9/8 09:53
 * @Version 1.0
 */
@Controller
public class ChatController {

    private final SimpMessagingTemplate messagingTemplate;

    public ChatController(SimpMessagingTemplate messagingTemplate) {
        this.messagingTemplate = messagingTemplate;
    }

    // 客户端 SEND 到 /app/hello -> 广播到 /topic/greetings
    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public ChatMsg greet(@Payload ChatMsg msg, Principal principal) {
        String who = principal != null ? principal.getName() : msg.getFrom();
        return new ChatMsg(who, null,
                (msg.getContent() == null ? "" : msg.getContent()));
    }

    // 客户端 SEND 到 /app/private -> 给指定用户发 /user/{username}/queue/msgs
    @MessageMapping("/private")
    public void privateChat(@Payload ChatMsg msg, Principal principal) {
        String from = principal != null ? principal.getName() : msg.getFrom();
        String to = msg.getTo();
        if (to == null || to.isEmpty()) {
            throw new IllegalArgumentException("Private message requires 'to' username");
        }
        messagingTemplate.convertAndSendToUser(to, "/queue/msgs",
                new ChatMsg(from, to, msg.getContent()));
    }
}
